import matplotlib.pyplot as plt
import pywt
import pandas as pd
import math

plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus'] = False
# Get data:
path = r"E:\机器学习\数据分析\scikit-learn 构建模型\data\水质参数集.csv"
data = pd.read_csv(path,sep=",",encoding="gbk")

# 极值阈值估计方法
def minimaxi(N):
    if N > 32:
        r = 0.3936 + 0.1829 * (math.log(N) / math.log(2))
        return r
    else:
        r = 0
        return r
data1 = data.iloc[42,2:]
index = []
data = []
for i in range(len(data1)-1):
    X = float(i)
    Y = float(data1[i])
    index.append(X)
    data.append(Y)

# reate wavelet object and define parameters
w = pywt.Wavelet('sym4')
N = len(data1) - 1
threshold = minimaxi(N)
# threshold = 0.3 # Threshold for filtering
# Decompose into wavelet components, to the level selected:
coeffs = pywt.wavedec(data, w, level=4)  # 将信号进行小波分解
for i in range(1, len(coeffs)):
    coeffs[i] = pywt.threshold(coeffs[i], threshold)  # 将噪声滤波
    datarec = pywt.waverec(coeffs, w)  # 将信号进行小波重构
mintime = 0
maxtime = mintime + len(data) + 2

plt.figure()
plt.subplot(2, 1, 1)
plt.plot(range(200,1243), data[mintime:maxtime])
plt.plot(range(200,1244), datarec[mintime:maxtime-1],"r")
plt.xlabel('波长(nm)')
plt.ylabel('吸光度')
plt.tight_layout()
plt.legend(['原始光谱',"重构光谱"])
plt.show()
